"use client"

import { DashIcon } from "@radix-ui/react-icons"
import { OTPInput, OTPInputContext } from "input-otp"
import * as React from "react"

import { ny } from "~/lib/utils"

const InputOTP = React.forwardRef<
   React.ElementRef<typeof OTPInput>,
   React.ComponentPropsWithoutRef<typeof OTPInput>
>(({ className, containerClassName, ...props }, ref) => (
   <OTPInput
      ref={ref}
      containerClassName={ny(
         "flex items-center gap-2 has-[:disabled]:opacity-50",
         containerClassName,
      )}
      className={ny("disabled:cursor-not-allowed", className)}
      {...props}
   />
))
InputOTP.displayName = "InputOTP"

const InputOTPGroup = React.forwardRef<
   React.ElementRef<"div">,
   React.ComponentPropsWithoutRef<"div">
>(({ className, ...props }, ref) => (
   <div ref={ref} className={ny("flex items-center", className)} {...props} />
))
InputOTPGroup.displayName = "InputOTPGroup"

const InputOTPSlot = React.forwardRef<
   React.ElementRef<"div">,
   React.ComponentPropsWithoutRef<"div"> & { index: number }
>(({ index, className, ...props }, ref) => {
   const inputOTPContext = React.useContext(OTPInputContext)
   const { char, hasFakeCaret, isActive } = inputOTPContext.slots[index]

   return (
      <div
         ref={ref}
         className={ny(
            "border-input relative flex size-9 items-center justify-center border-y border-r text-sm shadow-sm transition-all first:rounded-l-md first:border-l last:rounded-r-md",
            isActive && "ring-ring z-10 ring-1",
            className,
         )}
         {...props}
      >
         {char}
         {hasFakeCaret && (
            <div className="pointer-events-none absolute inset-0 flex items-center justify-center">
               <div className="animate-caret-blink bg-foreground h-4 w-px duration-1000" />
            </div>
         )}
      </div>
   )
})
InputOTPSlot.displayName = "InputOTPSlot"

const InputOTPSeparator = React.forwardRef<
   React.ElementRef<"div">,
   React.ComponentPropsWithoutRef<"div">
>(({ ...props }, ref) => (
   <div ref={ref} role="separator" {...props}>
      <DashIcon />
   </div>
))
InputOTPSeparator.displayName = "InputOTPSeparator"

export { InputOTP, InputOTPGroup, InputOTPSlot, InputOTPSeparator }
